package br.org.etec.dotcao.dao;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import br.org.etec.dotcao.dao.jpa.AnimalDaoImpl;
import br.org.etec.dotcao.dao.jpa.CityDaoImpl;
import br.org.etec.dotcao.dao.jpa.JPAImpl;
import br.org.etec.dotcao.dao.jpa.NewsDaoImpl;
import br.org.etec.dotcao.dao.jpa.RaceDaoImpl;
import br.org.etec.dotcao.dao.jpa.StateDaoImpl;
import br.org.etec.dotcao.dao.jpa.UserDaoImpl;
import br.org.etec.dotcao.model.Animal;
import br.org.etec.dotcao.model.City;
import br.org.etec.dotcao.model.News;
import br.org.etec.dotcao.model.Race;
import br.org.etec.dotcao.model.State;
import br.org.etec.dotcao.model.User;

public class DaoFactory {
	
	private static final EntityManagerFactory emf = Persistence.createEntityManagerFactory("dotcao");
	private static final EntityManager em = emf.createEntityManager();
	
	public synchronized static <T> Dao<T> get(Class<T> type){
		return get(type, em);
	}

	@SuppressWarnings("unchecked")
	public synchronized static <T> Dao<T> get(Class<T> type, EntityManager em){
		JPAImpl<T> result;
		
		if(User.class.isAssignableFrom(type)){
			result = (JPAImpl<T>) new UserDaoImpl();
		}
		else if(State.class.isAssignableFrom(type)){
			result = (JPAImpl<T>) new StateDaoImpl();
		}
		else if(Race.class.isAssignableFrom(type)){
			result = (JPAImpl<T>) new RaceDaoImpl();
		}
		else if(City.class.isAssignableFrom(type)){
			result = (JPAImpl<T>) new CityDaoImpl();
		}
		else if(News.class.isAssignableFrom(type)){
			result = (JPAImpl<T>) new NewsDaoImpl();
		}
		else if(Animal.class.isAssignableFrom(type)){
			result = (JPAImpl<T>) new AnimalDaoImpl();
		}
		else{
			result = new JPAImpl<T>(type);
		}
		
		result.setEntityManager(em);
		
		return result;
	}

}
